<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Sync extends MY_Controller {

    public function __construct()
    {
        parent::__construct();
        // 验证文件
        if (!file_exists($file_path = WEBPATH.'config/sync.php'))
        {
            $this->_json(0, '客户端sync.php文件不存在');
        }
        $this->my = require $file_path;
        // 密钥验证
        $sync = $this->input->post('sync');
        if (!$sync) {
            $this->_json(0, '客户端未收到网站密钥');
        } elseif (md5($this->my['sync']) != $sync) {
            $this->_json(0, '客户端网站密钥不正确');
        }
    }

    // 于服务端通信测试
	public function test()
	{

        // 数据库连接测试
        $mysqli = function_exists('mysqli_init') ? mysqli_init() : 0;
        if (!$mysqli) {
            $this->_json(0, '客户端的PHP环境必须启用Mysqli扩展');
        }

        $config = require WEBPATH.'config/database.php';

        if (!@mysqli_real_connect($mysqli, $config['hostname'], $config['username'], $config['password'])) {
            exit($this->_json(0, '客户端无法连接到数据库服务器（'.$config['hostname'].'）<br>请检查用户名（'.$config['username'].'）和密码（'.$config['password'].'）是否正确'));
        }
        if (!@mysqli_select_db($mysqli, $config['database'])) {
            if (!@mysqli_query($mysqli, 'CREATE DATABASE `'.$config['database'].'`')) {
                exit($this->_json(0, '客户端数据库（'.$config['database'].'）不存在，请手动建立数据库'));
            }
        }

        // utf8方式打开数据库
        mysqli_query($mysqli, 'SET NAMES utf8');

        $this->load->database();

        $this->_json(1, 'ok');

	}

	// 数据库结果检测
	public function mysql()
    {
        $tables = $this->input->post('table');
        if (!$tables) {
            $this->_json(0, '客户端未收到表结构数据');
        }

        $table = $this->db->dbprefix('index');
        $this->_query('DROP TABLE IF EXISTS `'.$table.'`;');
        $this->_query('CREATE TABLE IF NOT EXISTS `'.$table.'` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `mid` VARCHAR (30) NOT NULL COMMENT \'mid\',
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT=\'内容索引表\';');

        // 创建表
        foreach ($tables as $table => $t) {
            $this->_query('DROP TABLE IF EXISTS `'.$table.'`;');
            $this->_query($t);
        }

        $this->_json(1, 'ok');
    }

    // 内容替换
    public function replace_content() {

        $url = $this->input->post('url');
        if (!$url) {
            $this->_json(0, '客户端未收到内容数据(content)');
        }

        $data = dr_catcher_data($url);
        if (!$data) {
            $this->_json(0, '客户端无法获取远程数据(content)');
        }
        $json = json_decode($data, true);
        if (!$json) {
            $this->_json(0, '客户端JSON数据解析失败(content)');
        }

        foreach ($json as $table => $rows) {
            if ($rows) {
                foreach ($rows as $t) {
                    $this->db->replace($table, $t);
                    if (strpos($table, '_data') === false) {
                        $this->db->replace('index', array(
                            'id' => $t['id'],
                            'mid' => str_replace($this->db->dbprefix, '', $table),
                        ));
                    }

                }
            }
        }

        $this->_json(1, 'ok');
    }

    // 储存配置文件
    public function config() {

        $url = $this->input->post('url');
        if (!$url) {
            $this->_json(0, '客户端未收到内容数据(config)');
        }

        $data = dr_catcher_data($url);
        if (!$data) {
            $this->_json(0, '客户端无法获取远程数据(config)');
        }
        $json = json_decode($data, true);
        if (!$json) {
            $this->_json(0, '客户端JSON数据解析失败(config)');
        }

        $rt = file_put_contents(APPPATH.'cache/config.php', '<?php return '.var_export($json['config'], true).';');
        if (!$rt) {
            $this->_json(0, '客户端配置文件储存失败(config)');
        }

        $rt = file_put_contents(APPPATH.'cache/linkage.php', '<?php return '.var_export($json['linkage'], true).';');
        if (!$rt) {
            $this->_json(0, '客户端配置文件储存失败(linkage)');
        }

        $rt = file_put_contents(APPPATH.'cache/rewrite.php', '<?php return '.var_export($json['rewrite'], true).';');
        if (!$rt) {
            $this->_json(0, '客户端配置文件储存失败(rewrite)');
        }

        $rt = file_put_contents(APPPATH.'cache/uploadfile.php', '<?php return '.var_export($json['uploadfile'], true).';');
        if (!$rt) {
            $this->_json(0, '客户端配置文件储存失败(uploadfile)');
        }

        // 附件
        if ($json['uploadfile']) {
            foreach ($json['uploadfile'] as $name => $c) {
                file_put_contents(WEBPATH.'uploadfile/'.$name, dr_catcher_data($c));
            }
        }

        $this->_json(1, 'ok');
    }

    // 清空缓存
    public function clear() {

        $this->load->helper('file');

        delete_files(APPPATH.'cache/temp/');
        delete_files(APPPATH.'cache/data/');

        $this->_json(1, 'ok');
    }

    // 获取全部字段
    private function _get_field_data($table) {

    }

    // 执行sql
    private function _query($sql) {

        if (!$sql) {
            return NULL;
        }

        $sql_data = explode(';SQL_FINECMS_EOL', trim(str_replace(array(PHP_EOL, chr(13), chr(10)), 'SQL_FINECMS_EOL', $sql)));

        foreach($sql_data as $query){
            if (!$query) {
                continue;
            }
            $ret = '';
            $queries = explode('SQL_FINECMS_EOL', trim($query));
            foreach($queries as $query) {
                $ret.= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
            }
            if (!$ret) {
                continue;
            }
            $this->db->query($ret);
        }
    }
}
